package com.nnnu.orange.utils;

import com.nnnu.orange.constant.BookStatusConstants;
import com.nnnu.orange.pojo.entity.Books;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class ExcelParser {

    public List<Books> parseExcel(InputStream inputStream) throws Exception {
        Workbook workbook = new XSSFWorkbook(inputStream);  // 使用XSSFWorkbook解析xlsx文件
        Sheet sheet = workbook.getSheetAt(0);  // 获取第一个Sheet

        List<Books> booksList = new ArrayList<>();

        // 遍历Excel表格中的所有行
        for (Row row : sheet) {
            // 跳过标题行（假设标题在第一行）
            if (row.getRowNum() == 0) {
                continue;
            }

            // 根据列的顺序获取值，并将其转换为 Books 对象
            Books book = new Books();
            book.setTitle(row.getCell(0).getStringCellValue());
            book.setSubtitle(row.getCell(1).getStringCellValue());
            book.setAuthorId((int) row.getCell(2).getNumericCellValue());
            book.setCategoryId((int) row.getCell(3).getNumericCellValue());
            book.setIsbn(row.getCell(4).getStringCellValue());
            book.setPublishedDate(LocalDate.parse(row.getCell(5).getStringCellValue()));
            book.setLanguage(row.getCell(6).getStringCellValue());
            book.setShelfLocation(row.getCell(7).getStringCellValue());
            book.setDescription(row.getCell(8).getStringCellValue());
            book.setCoverImageUrl(row.getCell(9).getStringCellValue());
            book.setAddedDate(LocalDateTime.now());
            book.setFormat(row.getCell(10).getStringCellValue());
            book.setStatus(BookStatusConstants.PENDING_SHELF);
            book.setGenre(row.getCell(11).getStringCellValue());
            book.setEdition(row.getCell(12).getStringCellValue());
            book.setTags(row.getCell(13).getStringCellValue());

            booksList.add(book);
        }

        workbook.close();
        return booksList;
    }
}
